package org.autojs.websocket;

import java.net.URI;

import org.java_websocket.enums.ReadyState;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

public class SimpleWebSocketClient {
    private interface WebSocketListener {
        void onOpen(ServerHandshake serverHandshake);
        void onMessage(String msg);
        void onClose(int i, String s, boolean b);
        void onError(Exception e);
    }
    private WebSocketClient webSocketClient;
    public SimpleWebSocketClient(String uri, WebSocketListener listener) {
        this.setWebSocketClient(uri, listener);
        this.webSocketClient.connect();
        while (true) {
            if (this.webSocketClient.getReadyState().equals(ReadyState.OPEN)) break;
        }
    }
    private void setWebSocketClient(String uri, final WebSocketListener listener) {
        this.webSocketClient = new WebSocketClient(URI.create(uri)) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                listener.onOpen(serverHandshake);
            }
            @Override
            public void onMessage(String s) {
                listener.onMessage(s);
            }
            @Override
            public void onClose(int i, String s, boolean b) {
                listener.onClose(i, s, b);
            }
            @Override
            public void onError(Exception e) {
                listener.onError(e);
            }
        };
    }
    public void send(String message) {
        this.connect();
        this.webSocketClient.send(message);
    }
    public void send(byte[] message) {
        this.connect();
        this.webSocketClient.send(message);
    }
    public void connect() {
        if (this.webSocketClient.isClosed() || this.webSocketClient.isClosing()) {
            this.webSocketClient.connect();
        }
    }
    public void close() { this.webSocketClient.close(); }
    public Boolean isClosed() {
        return this.webSocketClient.isClosed();
    }
    public Boolean isClosing() {
        return this.webSocketClient.isClosing();
    }
    public Boolean isConnected() {
        return this.webSocketClient.isOpen();
    }
    public Boolean isFlushAndClose() {
        return this.webSocketClient.isFlushAndClose();
    }
    public Boolean isReuseAddr() {
        return this.webSocketClient.isReuseAddr();
    }
    public Boolean isTcpNoDelay() {
        return this.webSocketClient.isTcpNoDelay();
    }
}
